package com.caiheng.api.controller.event;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.dao.event.EventCleanAreaListInfoMapper;
import com.caiheng.api.dao.event.EventPatrolLineInfoMapper;
import com.caiheng.api.dao.event.EventPatrolPointMapper;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.event.*;
import com.caiheng.api.entity.survey.SurveyQuestion;
import com.caiheng.api.entity.survey.SurveyUserRecord;
import com.caiheng.api.entity.sys.SysDept;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.titlemenu.TitleMenu;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.event.*;
import com.caiheng.api.service.survey.SurveyUserRecordService;
import com.caiheng.api.service.sys.SysDeptService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.titlemenu.TitleMenuService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  设备相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/plan")//url:模块/资源/{}/细分
public class EventTaskController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SurveyUserRecordService surveyUserRecordService;
    @Resource
    private EventPlanTaskService planTaskService;
    @Resource
    private EventPlanTaskInfoService planTaskInfoService;
    @Resource
    private EventPlanTaskImgService planTaskImgService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private EstateService estateService;
    @Resource
    private EventTerminalsService terminalsService;
    @Resource
    private EventPatrolLineInfoService patrolLineInfoService;
    @Resource
    private EventCleanAreaListInfoService cleanAreaListInfoService;
    @Resource
    private EventCleanAreaService cleanAreaService;
    @Resource
    private EventPatrolPointService patrolPointService;
    @Resource
    private TitleMenuService titleMenuService;
    @Resource
    private EventPointQrService eventPointQrService;
    @Resource
    private EventPointQrInfoService eventPointQrInfoService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private PaySlipService paySlipService;
    @Resource
    private SysDeptService sysDeptService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址

    @Value("${web.imgPrefixOss}")
    private String imgPrefixOss;//图片地址

    /**
     *  我的物业中心界面 初始化数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： " + requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int task_id = jsonRequest.containsKey("task_id") ? jsonRequest.getInt("task_id") : 0;


            //判断当前操作任务是否是今天的
            EventPlanTask task = planTaskService.findById(task_id);
            if(task != null){
                if(new Date().getTime() < task.getBeginTime().getTime() || task.getEndTime().getTime() < new Date().getTime()){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请在规定时间内进行打卡"),true,true);
                }
            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我的物业中心界面 初始化数据
     * @param
     * @throws Exception
     */
    @PostMapping(value="/manager/view")
    public JSONObject managerView(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： " + requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            User user = null;
            SysUser sysUser = null;
            boolean blVisitRecord = false;
            boolean blKefu = false;
            if(user_id > 0){
                user = userService.findById(user_id);
                if(user == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
                }

                sysUser = sysUserService.findById(user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定工作人员账号"),true,true);
                }

                //可查询访客记录的人员部门
                blVisitRecord = sysDeptService.isDeptUserBySysUserId(sysUser, 2);
                map.put("isVisitRecord", blVisitRecord ? 1 : 0);

                //我的个人信息
                map.put("sys_user_name", sysUser.getNickName());
                map.put("nick_name", user.getNickName());
                map.put("phone_num", user.getPhoneNum());
                map.put("estate_id", user.getEstateId());
//            EstateUser estateUser = estateUserService.getEstateByUser()
                Estate estate = estateService.findById(sysUser.getEstateId());
                if(estate != null){
                    map.put("estate_name", estate.getEstateName());
                    map.put("estate_id", sysUser.getEstateId());
                }

                if(StrUtil.isNotEmpty(user.getFaceUrl())){
                    if(!user.getFaceUrl().contains("https")){
                        map.put("face_url", imgPrefixOss + user.getFaceUrl());
                    }else{
                        map.put("face_url",  user.getFaceUrl());
                    }
                }

                // 代办事项数
                Map<String, Object> mapParam0 = new HashMap<>();
                mapParam0.put("sys_user_id", sysUser.getUserId());
                mapParam0.put("state",0);
                mapParam0.put("beginTime", DateUtil.getBeforeDayDate(0));
                mapParam0.put("endTime", DateUtil.getAfterDayDate(0));
                long count0 = planTaskService.getTaskCount(mapParam0);
                map.put("count0", count0);

                // 已办事项数
                Map<String, Object> mapParam1 = new HashMap<>();
                mapParam1.put("sys_user_id", sysUser.getUserId());
                mapParam1.put("state",1);
                mapParam1.put("beginTime", DateUtil.getBeforeDayDate(0));
                mapParam1.put("endTime", DateUtil.getAfterDayDate(0));
                long count1 = planTaskService.getTaskCount(mapParam1);
                map.put("count1", count1);

                //可查询访客记录的人员部门  客服部门人员
                blKefu = sysDeptService.isDeptUserBySysUserId(sysUser, 7);
                map.put("isCustomer", blKefu ? 1 : 0);

            }


            //1.标题TAB菜单
            List<TitleMenu> menuListNew = new ArrayList<>();
            List<TitleMenu> menuList = titleMenuService.selectBySpecial("estate_manager", user);
            for (TitleMenu titleMenu : menuList) {
                if(StrUtil.isNotEmpty(titleMenu.getPurviewType())){
                    if(titleMenu.getPurviewType().equals("visit_record")){
                        if(blVisitRecord){
                            menuListNew.add(titleMenu);
                        }
                    } else if(titleMenu.getPurviewType().equals("customer_service")){
                        if(blKefu){
                            menuListNew.add(titleMenu);
                        }
                    }else{
                        menuListNew.add(titleMenu);
                    }
                }else{
                    menuListNew.add(titleMenu);
                }
            }
            map.put("menuList", menuListNew);


            map.put("isHasPaySlip", 0);
            if(user != null){
                QueryWrapper<PaySlip> qw = new QueryWrapper<>();
                qw.eq("phone_num", user.getPhoneNum());
                qw.eq("state", 0);
                qw.last("limit 1");
                PaySlip paySlip = paySlipService.getOne(qw);
                if(paySlip != null){
                    map.put("isHasPaySlip", 1);
                    map.put("paySlip", paySlip);
                }
            }



            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  查询我的任务列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/task/list")
    public JSONObject recordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： " + requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;
            int state  = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            //1	巡检  2	巡更 3	保洁  4	消杀  5	维保
            int eventType  = jsonRequest.containsKey("eventType") ? jsonRequest.getInt("eventType") : 0;
            //today - 今日 week  本周  month - 本月  range - 指定日期
            String dateType = jsonRequest.containsKey("dateType") ? jsonRequest.getStr("dateType") : "";
            //range - 指定日期 有效
            String beginDate = jsonRequest.containsKey("beginDate") ? jsonRequest.getStr("beginDate") : "";
            String endDate = jsonRequest.containsKey("endDate") ? jsonRequest.getStr("endDate") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定工作人员账号"),true,true);
            }

//            QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
//            qw.eq("worker_sys_user_id", sysUser.getUserId());
//            if(eventType > 0){
//                qw.eq("event_type", eventType);
//            }
//            qw.eq("state",state);
//            qw.orderByAsc("begin_time");

            Map<String, Object> mapParam = new HashMap<>();
            mapParam.put("sys_user_id", sysUser.getUserId());
            mapParam.put("state",state);
            if(eventType > 0) {
                mapParam.put("event_type", eventType);
            }
            if(dateType.equals("today")){//今日任务
                mapParam.put("beginTime", DateUtil.getBeforeDayDate(0));
                mapParam.put("endTime", DateUtil.getAfterDayDate(0));
            } else if(dateType.equals("week")){//本周任务
                mapParam.put("beginTime", DateUtil.getWeekBegin()  + " 00:00:00");
                mapParam.put("endTime", DateUtil.getWeekEnd() + " 23:59:59");
            } else if(dateType.equals("month")){//本月任务
                mapParam.put("beginTime", DateUtil.getMonthFirstDayStr()  + " 00:00:00");
                mapParam.put("endTime", DateUtil.getMonthLastDayStr()  + " 23:59:59");
            } else if(dateType.equals("range")){//指定日期
                mapParam.put("beginTime", beginDate + " 00:00:00");
                mapParam.put("endTime", endDate + " 23:59:59");
            }

            int offset = (pageIndex - 1) * pageSize;
            List<EventPlanTask> list = planTaskService.selectTaskList(mapParam, offset, pageSize);
            map.put("tasks", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  查询我的任务列表(根据统一二维码获取当前绑定在二维码下的所有任务)
     * @param
     * @throws Exception
     */
    @PostMapping(value="/task/list/new")
    public JSONObject recordListNew(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： " + requestParam);

            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;
            int state  = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;

            //today - 今日 week  本周  month - 本月  range - 指定日期
            String dateType = jsonRequest.containsKey("dateType") ? jsonRequest.getStr("dateType") : "";
            //range - 指定日期 有效
            String beginDate = jsonRequest.containsKey("beginDate") ? jsonRequest.getStr("beginDate") : "";
            String endDate = jsonRequest.containsKey("endDate") ? jsonRequest.getStr("endDate") : "";
            // 统一二维码id
            int point_qr_id  = jsonRequest.containsKey("point_qr_id") ? jsonRequest.getInt("point_qr_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定工作人员账号"),true,true);
            }

//            QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
//            qw.eq("worker_sys_user_id", sysUser.getUserId());
//            if(eventType > 0){
//                qw.eq("event_type", eventType);
//            }
//            qw.eq("state",state);
//            qw.orderByAsc("begin_time");

            Map<String, Object> mapParam = new HashMap<>();
            mapParam.put("sys_user_id", sysUser.getUserId());
            mapParam.put("state",state);
            mapParam.put("point_qr_id",point_qr_id);
//            if(eventType > 0) {
//                mapParam.put("event_type", eventType);
//            }
            if(dateType.equals("today")){//今日任务
                mapParam.put("beginTime", DateUtil.getBeforeDayDate(0));
                mapParam.put("endTime", DateUtil.getAfterDayDate(0));
            } else if(dateType.equals("week")){//本周任务
                mapParam.put("beginTime", DateUtil.getWeekBegin()  + " 00:00:00");
                mapParam.put("endTime", DateUtil.getWeekEnd() + " 23:59:59");
            } else if(dateType.equals("month")){//本月任务
                mapParam.put("beginTime", DateUtil.getMonthFirstDayStr()  + " 00:00:00");
                mapParam.put("endTime", DateUtil.getMonthLastDayStr()  + " 23:59:59");
            } else if(dateType.equals("range")){//指定日期
                mapParam.put("beginTime", beginDate + " 00:00:00");
                mapParam.put("endTime", endDate + " 23:59:59");
            }

            int offset = (pageIndex - 1) * pageSize;
            List<EventPlanTask> list = planTaskService.selectTaskListByQrCode(mapParam, offset, pageSize);
            map.put("tasks", list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 任务详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/task/detail")
    public Object repairDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "task/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int task_id = jsonRequest.containsKey("task_id") ? jsonRequest.getInt("task_id") : 0;
            int isShare = jsonRequest.containsKey("isShare") ? jsonRequest.getInt("isShare") : 0;

            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0d;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }
            SysUser sysUser = null;
            if(isShare == 0){
                sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
                if(sysUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
                }
            }

            EventPlanTask task = planTaskService.getTaskDetail(task_id, sysUser, lng, lat);
            if(task == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该任务不存在"),true,true);
            }

            task.setIsMyTask(0);

            if(sysUser!= null && task.getWorkerSysUserId().intValue() == sysUser.getUserId().intValue()){
                task.setIsMyTask(1);
            }


            List<EventPlanTaskImg> imgs = planTaskImgService.selectListByColumn("task_id",task.getId());
            if(CollUtil.isNotEmpty(imgs)){
                imgs.forEach(img->{
                    img.setImgUrl(imgPrefix +img.getImgUrl());
                });
            }
            task.setImgs(imgs);


            map.put("task",task);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 统一码 位置点详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/point/detail")
    public Object pointDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "task/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int point_id = jsonRequest.containsKey("point_id") ? jsonRequest.getInt("point_id") : 0;

            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0d;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            SysUser sysUser = sysUserService.selectByUniqueColumn("user_id",user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定企业人员"),true,true);
            }

            EventPointQr pointQr = eventPointQrService.getPointQr(point_id, lng, lat);
            if(pointQr == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该位置不存在"),true,true);
            }

            map.put("pointQr",pointQr);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 统一码 业主扫码  显示当前位置的执行进度
     * @param
     * @throws Exception
     */
    @PostMapping(value="/point/preview")
    public Object pointPreview(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "task/point/preview 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int point_id = jsonRequest.containsKey("point_id") ? jsonRequest.getInt("point_id") : 0;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
//            }

            QueryWrapper<SurveyUserRecord> qw = new QueryWrapper<>();
            qw.eq("point_qr_id", point_id);
            qw.orderByDesc("create_time");
            List<SurveyUserRecord> userRecords = surveyUserRecordService.list(qw);
            if(CollUtil.isNotEmpty(userRecords)){
                for (SurveyUserRecord userRecord : userRecords){

                    EventPlanTask eventPlanTask = planTaskService.getById(userRecord.getEventTaskId());
                    if(eventPlanTask != null){
                        Estate estate = estateService.findById(eventPlanTask.getEstateId());
                        if(estate != null){
                            userRecord.setEstateName(estate.getEstateName());
                        }
                        userRecord.setSysUserName(eventPlanTask.getWorkerName());
                    }


                    EventPlanTaskInfo taskInfo = planTaskInfoService.getById(userRecord.getEventTaskInfoId());
                    if(taskInfo != null){
//                        事务目标的类型  0 - 设备  1 - 巡更点  2 - 楼层（build_floor表）  3 - 自定义区域（build 表） 需要的往后加
//                        对应事务中实体的lid  设备id，  巡更点id   ,楼层id 等等

                        if(taskInfo.getTargetType() == 0){
                            EventTerminals terminals = terminalsService.findById(taskInfo.getTargetId());
                            if(terminals!= null){
                                userRecord.setSectionContent(terminals.getTerminalName());
                            }
                        } else if(taskInfo.getTargetType() == 1){
                            EventPatrolLineInfo eventPatrolLineInfo = patrolLineInfoService.findById(taskInfo.getTargetId());
                            if(eventPatrolLineInfo != null){
                                EventPatrolPoint point = patrolPointService.findById(eventPatrolLineInfo.getPointId());
                                if(point != null){
                                    userRecord.setSectionContent(point.getPatrolTitle());
                                }
                            }
                        } else if(taskInfo.getTargetType() == 2){
                            EventCleanAreaListInfo cleanAreaListInfo = cleanAreaListInfoService.findById(taskInfo.getTargetId());
                            if(cleanAreaListInfo != null){
                                EventCleanArea cleanArea = cleanAreaService.findById(cleanAreaListInfo.getAreaId());
                                if(cleanArea != null){
                                    userRecord.setSectionContent(cleanArea.getAreaTitle());
                                }
                            }
                        }
                    }

                    EventPointQrInfo pointQrInfo = eventPointQrInfoService.getById(userRecord.getPointQrInfoId());;
                    if(pointQrInfo != null){
                        //任务类型 1-巡检  2-巡更 3-保洁 4-绿化 5-消杀  6-维保
                        if(pointQrInfo.getEventType() == 1){
                            userRecord.setEventTypeName("巡检");
                        } else if(pointQrInfo.getEventType() == 2){
                            userRecord.setEventTypeName("巡更");
                        } else if(pointQrInfo.getEventType() == 3){
                            userRecord.setEventTypeName("保洁");
                        } else if(pointQrInfo.getEventType() == 4){
                            userRecord.setEventTypeName("绿化");
                        } else if(pointQrInfo.getEventType() == 5){
                            userRecord.setEventTypeName("消杀");
                        } else if(pointQrInfo.getEventType() == 6){
                            userRecord.setEventTypeName("维保");
                        }
                    }
                }
            }

            map.put("userRecords", userRecords);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",userRecords.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }




    /**
     * 巡检记录的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public Object uploadImg(@RequestParam("task_id") int task_id,@RequestParam("img_type") int img_type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            EventPlanTask task = planTaskService.getById(task_id);
            if(task == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "任务不存在"), true, true);
            }
            System.out.println("task_id==" + task_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "mp4".equals(prefix)) {
                                String fileName = "record_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_TERMINAL_RECORD_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certurl.getInputStream(),fileName,upload_type);

                                        EventPlanTaskImg img = new EventPlanTaskImg();
                                        img.setTaskId(task_id);
                                        img.setImgUrl(img_key);
                                        img.setImgType(img_type);
                                        img.setImgSuffix(prefix);
                                        planTaskImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
